/*==============================================================================
FILE NAME: Figure_A7.do
CREATED: 22 July 2025
==============================================================================*/

**Figure A7

/* Set directory if working independently through code
if c(username)=="" { //insert username
	global rootdir "" // insert root path
	global processed_data "$rootdir/processed_data" 
	global figures "$rootdir/output/figures"  // Define global paths for replication package
} 
*/

//distributed lag model
use "$processed_data/Air_Panel.dta", clear

// Drop observations with no air investigations
drop if never_air_inv == 1

// Create time variable
egen t = group(year month)
xtset RN_id t

sort RN_id
unique RN_id if p_air_incident==1
collapse (max) p_air_incident, by(RN_id)
rename p_air_incident ever_air_incident
label var ever_air_incident "=1 if RN_id was ever the subject of a complaint during sample period"
sort RN_id
unique RN_id if ever_air_incident==1
save "$processed_data/temp.dta", replace
use "$processed_data/Air_Panel", clear
sort RN_id
merge m:1 RN_id using "$processed_data/temp.dta", nogenerate // merge in ever_air_incident

// Create time variable

egen t = group(year month)
xtset RN_id t
sort RN_id t

forvalues x = 1/12 {
	gen aircomp_minus`x' = (l`x'.p_air_incident)    // Lags 1 to 12 months before incident
	gen aircomp_plus`x'  = (f`x'.p_air_incident)    // Leads 1 to 12 months after incident
}

replace aircomp_minus1 = . if t == 1               // Drop invalid lag in first time period

// Drop invalid lag values for earlier time periods
forvalues x = 2/12 {
	replace aircomp_minus`x' = . if t <= `x'
}

// Run regressions for lags
reghdfe p_air_inv aircomp_plus12 aircomp_plus11 aircomp_plus10 aircomp_plus9 aircomp_plus8 aircomp_plus7 aircomp_plus6 aircomp_plus5 aircomp_plus4 aircomp_plus3 aircomp_plus2 aircomp_plus1 p_air_incident aircomp_minus1 aircomp_minus2 aircomp_minus3 aircomp_minus4 aircomp_minus5 aircomp_minus6 aircomp_minus7 aircomp_minus8 aircomp_minus9 aircomp_minus10 aircomp_minus11 aircomp_minus12, cluster(RN_id) absorb(RN_id t)

regsave, ci
gen Years = _n
drop if Years == 26
replace Years = Years -13
gen Zero = 0
export delimited "$point_estimates/Point_Estimates_Figure_A7.csv", replace
graph set window fontface "Times New Roman"
twoway(rarea ci_upper ci_lower Years, col(navy) fint(inten20) lwidth(0) lpattern(solid))(line coef Years, lcolor(navy) lpattern(solid) lwidth(medium))(line Zero Years, lcolor(black)), xlabel(-12(1)12, nogrid labsize(vlarge)) ylabel(0(0.1)0.6, labsize(vlarge)) legend(off) ytitle("{&Delta} P(Investigation)", size(vlarge)) xtitle("Month", size(vlarge)) graphregion(color(white)) plotregion(color(white)) xsize(8.6)
// Save figure
graph export "$figures/Figure_A7.pdf", replace
